package com.heima.search.listen;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.message.ArticleForEsConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    ArticleSearchService articleSearchService;


    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD)
    public void addHandler(String message){
        log.info("接收到索引库同步消息  添加索引库文章  消息内容==>{}",message);
        if(StringUtils.isNotBlank(message)){
            Map map = JSON.parseObject(message, Map.class);
            Long articleId = (Long)map.get("articleId");
            ResponseResult<SearchArticleVo> articleResult = articleFeign.findArticle(articleId);
            if (articleResult.getCode().intValue()!=0) {
                log.error("远程查询 文章信息失败  ==>{}",articleId);
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,articleResult.getErrorMessage());
            }
            SearchArticleVo searchArticleVo = articleResult.getData();
            if(searchArticleVo == null){
                log.error("远程查询 文章信息不存在  ==>{}",articleId);
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //   保存文章到索引库
            articleSearchService.saveArticle(searchArticleVo);
        }
    }
    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE)
    public void deleteHandler(String message){
        log.info("接收到索引库同步消息  删除索引库文章  消息内容==>{}",message);
        if(StringUtils.isNotBlank(message)){
            Map map = JSON.parseObject(message, Map.class);
            Long articleId = (Long)map.get("articleId");
            //   从索引库中删除文章
            articleSearchService.deleteArticle(articleId);
        }
    }

}
